package org.NooLab.itexx.utilities;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import org.apache.tika.detect.DefaultDetector;
import org.apache.tika.io.TikaInputStream;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.mime.MimeTypes;

public class MimeDetector {

	private static final DefaultDetector DETECTOR = new DefaultDetector(MimeTypes.getDefaultMimeTypes());

	// =======================================================================
	public MimeDetector() {

	}

	// =======================================================================

	public static String detectFileMimeType(final File file) throws IOException {

		TikaInputStream inStream = null;
		inStream = TikaInputStream.get(file);

		return detectMimeType(inStream);
	}

	private static String detectMimeType(final InputStream inStream) throws IOException {

		try {
			/*
			 * You might not want to provide the file's name. If you provide an
			 * Excel document with a .xls extension, it will get it correct
			 * right away; but if you provide an Excel document with .doc
			 * extension, it will guess it to be a Word document
			 */
			final Metadata metadata = new Metadata();
			// metadata.set(Metadata.RESOURCE_NAME_KEY, file.getName());
			return DETECTOR.detect(inStream, metadata).toString();
		} finally {
			if (inStream != null) {
				inStream.close();
			}
		}
	}

	public static String detectRemoteFileMimeType(String urlString) {

		int n, r = -1;
		String mime = "";

		URL url;
		URLConnection connection;
		InputStream inStream = null;

		try {
			url = new URL(urlString);
			inStream = url.openStream();

			ByteArrayOutputStream outStream = new ByteArrayOutputStream();

			byte[] buf = new byte[4096];

			while (((n = inStream.read(buf)) >= 0) && (outStream.size() < 3000)) {
				outStream.write(buf, 0, n);
			}
			outStream.close();
			inStream.close();
			// byte[] data = outStream.toByteArray();
			r = 0;
		} catch (Exception e) {
			e.printStackTrace();
			r = -7;
		}

		if ((r == 0) && (inStream!=null)){
			try {
				mime = detectMimeType(inStream);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return mime;
	}
}
